package cn.kai.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.Objects;

/**
 * Author: cKnight
 * Date: 2024/8/27
 */
@Slf4j
public class XMLUtil {

    /**
     * 获取node
     * @param document
     * @param name
     * @param type
     * @return
     */
    public static Node getNode(Document document,String name,int type){
        NodeList childNodes = document.getDocumentElement().getChildNodes();
        return getNode(childNodes,name,type);
    }

    public static Node getNode(NodeList node,String name,int type){
        if (Objects.isNull(node) || StringUtils.isEmpty(name)){
            return null;
        }
        for (int i = 0; i < node.getLength(); i++) {
            Node item = getNode(node.item(i), name, type);
            if (Objects.nonNull(item)){
                return item;
            }
        }
        return null;
    }


    public static Node getNode(Node node,String name,int type){
        if (name.equalsIgnoreCase(node.getNodeName()) && node.getNodeType() == type){
            return node;
        }
        if (node.getNodeType() == Node.ELEMENT_NODE){
            return getNode(node.getChildNodes(),name,type);
        }
        return null;
    }


    public static File write(Document document){
        File file = null;
        try {
            //临时文件
            file = File.createTempFile("temp", null);
            //创建转换器
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            //格式
//            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            DOMSource domSource = new DOMSource(document);
            StreamResult streamResult = new StreamResult(file);
            //执行转化
            transformer.transform(domSource,streamResult);
            // JVM 退出时删除
            file.deleteOnExit();
        }catch (Exception e){
            log.error("xml文件写出异常:",e);
        }
        return file;
    }
}
